//
//  YBCodeShowController.m
//  Cocoachina
//
//  Created by 游兵 on 2017/9/15.
//  Copyright © 2017年 YBing. All rights reserved.
//

#import "YBCodeShowController.h"
#import <MJRefresh.h>
#import "YBCode.h"
#import "YBCodeCell.h"
#import "YBJSController.h"
#import "YBWaterLayout.h"
#import "YBCodeSortView.h"
#import "YBMemoryTool.h"

@interface YBCodeShowController ()<UICollectionViewDelegate, UICollectionViewDataSource, YBWaterLayoutDelegate>

@property (nonatomic, strong) NSMutableArray<YBCode *> *datas;
/** 0发布时间 1下载量 2浏览量*/
@property (nonatomic, assign) NSInteger sort;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation YBCodeShowController

- (void)setUrl:(NSString *)url
{
    _url = [url copy];
    [self.collectionView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self loadData];
    
}

- (void)setupUI
{
    YBWeakSelf
    YBCodeSortView *sortView = [YBCodeSortView sortViewWithFrame:CGRectMake(0, 0, kScreenW, 44) didClickedBlock:^(NSInteger index) {
        weakSelf.sort = index;
        [weakSelf.collectionView.mj_header beginRefreshing];
    }];
    [self.view addSubview:sortView];
    
    YBWaterLayout *layout = [[YBWaterLayout alloc] initWithColumnCount:2];
    layout.rowSpacing = 8;
    layout.columnSpacing = 8;
    layout.sectionInset = UIEdgeInsetsMake(0, 8, 0, 8);
    layout.delegate = self;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(sortView.frame), kScreenW, kScreenH-64-sortView.height-49) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"YBCodeCell" bundle:nil] forCellWithReuseIdentifier:@"YBCodeCell"];
    [self.view addSubview:self.collectionView];
    
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadData];
    }];
}

- (void)loadData
{
    NSString *url = [self.url stringByAppendingFormat:@"/%zi", 1];
    if (self.sort==1) {
        url = [url stringByAppendingString:@"?order=downloads"];
    } else if (self.sort==2) {
        url = [url stringByAppendingString:@"?order=hits"];
    }
    [YBHttpTool get:url success:^(TFHpple *doc) {
        [self.collectionView.mj_header endRefreshing];
        if (self.getDataBlock) {
            self.getDataBlock(doc);
        }
        NSMutableArray *datas = [self parseWithHpple:doc];;
        self.datas = datas;
        
        YBWeakSelf
        if (self.collectionView.mj_footer==nil) {
            self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [weakSelf loadMoreData];
            }];
        }
        if (datas.count==0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.collectionView.mj_footer resetNoMoreData];
        }
        self.page = 2;
        
        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    NSString *url = [self.url stringByAppendingFormat:@"/%zi", self.page];
    if (self.sort==1) {
        url = [url stringByAppendingString:@"?order=downloads"];
    } else if (self.sort==2) {
        url = [url stringByAppendingString:@"?order=hits"];
    }
    [YBHttpTool get:url success:^(TFHpple *doc) {
        [self.collectionView.mj_footer endRefreshing];
        NSMutableArray *datas = [self parseWithHpple:doc];
        [self.datas addObjectsFromArray:datas];
        
        if (datas.count==0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            self.page++;
            [self.collectionView.mj_footer resetNoMoreData];
        }
        
        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
        [self.collectionView.mj_footer endRefreshing];
    }];
}

- (NSMutableArray<YBCode *> *)parseWithHpple:(TFHpple *)doc
{
    TFHppleElement *water = [[doc searchWithXPathQuery:@"//div[@class='waterfall-container']"] firstObject];
    NSArray<TFHppleElement *> *list = [water childrenWithClassName:@"waterfall-box"];
    NSMutableArray<YBCode *> *datas = [NSMutableArray array];
    
    [list enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YBCode *code = [YBCode new];
        TFHppleElement *a = [obj firstChildWithTagName:@"a"];
        code.url = [a objectForKey:@"href"];
        code.img = [[a firstChildWithTagName:@"img"] objectForKey:@"src"];
        code.title = [[obj firstChildWithClassName:@"w-name"] firstChildWithTagName:@"a"].text;
        
        TFHppleElement *puptime = [obj firstChildWithClassName:@"w-puptime"];
        code.time = [[puptime firstChildWithTagName:@"text"].content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        code.download = [puptime firstChildWithTagName:@"span"].text;
        code.desc = [obj firstChildWithClassName:@"w-desc"].text;
        [datas addObject:code];
    }];
    return datas;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBCodeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YBCodeCell" forIndexPath:indexPath];
    cell.code = self.datas[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    YBJSController *vc = [YBJSController new];
    vc.url = [NSString stringWithFormat:@"%@%@", @"http://code.cocoachina.com/", self.datas[indexPath.row].url];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)waterLayout:(YBWaterLayout *)waterLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath
{
    return self.datas[indexPath.row].height;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat memory = [YBMemoryTool usedMemory];
    if (memory>300) {
        [YBMemoryTool clearMemory];
        YBLog(@"%@", @"清除内存来了.....");
    }
//    if (memory>600) {
//        [YBMemoryTool clearMemoryAndCancelAll];
//    }
}


@end
